package com.wangxiaonan.berry.config;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;

/**
 * FeignRepository 扫描实现
 *
 * @Author: wangxiaonan
 * @Date: 2019/7/2
 **/
public class FeignRepositoryScanner implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

    private static final String BASE_PACKAGE_KEY = "basePackage";

    private ResourceLoader resourceLoader;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata,
            BeanDefinitionRegistry beanDefinitionRegistry) {
        AnnotationAttributes attributes = AnnotationAttributes
                .fromMap(annotationMetadata.getAnnotationAttributes(FeignRepositoryScan.class.getName()));

        if (attributes == null) {
            return;
        }
        String[] basePackages = attributes.getStringArray(BASE_PACKAGE_KEY);
        if (basePackages == null || basePackages.length == 0) {
            basePackages = new String[]{((StandardAnnotationMetadata) annotationMetadata).getIntrospectedClass()
                    .getPackage().getName()};
        }

        FeignRepositoryClassPathScanHandle scanHandle = new FeignRepositoryClassPathScanHandle(beanDefinitionRegistry,
                false);

        if (resourceLoader != null) {
            scanHandle.setResourceLoader(resourceLoader);
        }

//        scanHandle.setBeanNameGenerator(new RpcBeanNameGenerator());
        //扫描指定路径下的接口
        scanHandle.doScan(basePackages);

    }
}
